/*
 * @Author: Kiro AI Assistant
 * @Date: 2025-01-10
 * @Description: 音乐API服务测试
 */

import 'package:flutter_test/flutter_test.dart';
import 'package:music_example/services/music_api_service.dart';
import 'package:music_example/services/music_api_exception.dart';

void main() {
  group('MusicApiService Tests', () {
    late MusicApiService apiService;

    setUp(() {
      apiService = MusicApiService();
      apiService.initialize();
    });

    tearDown(() {
      apiService.dispose();
    });

    group('搜索功能测试', () {
      test('应该能够搜索音乐并返回结果', () async {
        // 测试搜索功能
        final results = await apiService.loadSearchData(
          keyword: '周杰伦',
          page: 1,
        );

        expect(results, isA<List>());
        // 注意：由于网络请求的不确定性，这里不强制要求有结果
        // 在实际测试中可能需要使用 mock 数据
      });

      test('空关键词应该返回空列表', () async {
        final results = await apiService.loadSearchData(
          keyword: '',
          page: 1,
        );

        expect(results, isEmpty);
      });

      test('不支持的音乐来源应该抛出异常', () async {
        expect(
          () => apiService.loadSearchData(
            keyword: '测试',
            sourceType: 'unsupported',
          ),
          throwsA(isA<SearchException>()),
        );
      });
    });

    group('播放链接获取测试', () {
      test('不支持的音乐来源应该抛出异常', () async {
        expect(
          () => apiService.loadStrapTrack(
            trackId: 'test123',
            sourceType: 'unsupported',
          ),
          throwsA(isA<PlayUrlException>()),
        );
      });

      test('空的trackId应该处理正确', () async {
        // 这个测试可能会抛出异常，这是预期的行为
        expect(
          () => apiService.loadStrapTrack(trackId: ''),
          throwsA(isA<Exception>()),
        );
      });
    });

    group('工具方法测试', () {
      test('应该能够生成QQ音乐图片URL', () {
        final url = MusicApiService.getQQImageUrl(
          qqImageId: 'test123',
          imageType: 'album',
        );

        expect(url, isNotEmpty);
        expect(url, contains('imgcache.qq.com'));
        expect(url, contains('test123'));
      });

      test('空的图片ID应该返回空字符串', () {
        final url = MusicApiService.getQQImageUrl(qqImageId: '');
        expect(url, isEmpty);
      });

      test('应该能够格式化音乐时长', () {
        final duration = Duration(minutes: 3, seconds: 45);
        final formatted = MusicApiService.formatMusicDuration(duration);

        expect(formatted, equals('03:45'));
      });

      test('应该能够格式化小时级别的时长', () {
        final duration = Duration(hours: 1, minutes: 23, seconds: 45);
        final formatted = MusicApiService.formatMusicDuration(duration);

        expect(formatted, equals('1:23:45'));
      });
    });

    group('网络连接测试', () {
      test('应该能够检查网络连接', () async {
        final isConnected = await apiService.checkNetworkConnection();
        expect(isConnected, isA<bool>());
      });
    });
  });
}
